package x.ovo.wechat.bot;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import x.ovo.wechat.bot.common.entity.Contact;
import x.ovo.wechat.bot.common.entity.event.MessageEvent;
import x.ovo.wechat.bot.common.entity.message.TextMessage;
import x.ovo.wechat.bot.common.event.Event;
import x.ovo.wechat.bot.common.event.EventListener;

import java.io.IOException;
import java.time.Instant;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j(topic = "骚话")
public class SaohuaListener extends EventListener<MessageEvent<TextMessage>> {

    private static final String QINGHUA_URL_2 = "https://api.vvhan.com/api/text/love";
    private static final String JOKE_URL = "https://api.vvhan.com/api/text/joke";
    private static final Pattern SAOHUA_PATTERN = Pattern.compile("<p>?(.*)</p>?");
    private static final Pattern QINGHUA_PATTERN = Pattern.compile("(.*)");

    private static final String[] URLS = {
            "https://v.api.aa1.cn/api/api-saohua/?type=text",
            "https://api.vvhan.com/api/text/sexy",
            "https://zj.v.api.aa1.cn/api/wenan-pp/?type=text",
            "https://zj.v.api.aa1.cn/api/wenan-gaoxiao/?type=text"
    };

    @Override
    public boolean support(Event<?> event) {
        return event instanceof MessageEvent
                && event.getSource() instanceof TextMessage
                && (
                ((MessageEvent<?>) event).getContent().contains("骚话")
                        || ((MessageEvent<?>) event).getContent().contains("毒鸡汤")
                        || ((MessageEvent<?>) event).getContent().contains("段子")
                        || ((MessageEvent<?>) event).getContent().contains("情话")
                        || ((MessageEvent<?>) event).getContent().contains("笑话")
        );
    }

    @Override
    public void onEvent(MessageEvent<TextMessage> event) {
        Contact fromUser = event.getSource().getFromUser();
        if (event.getContent().contains("骚话")) {
            try {
                int l = (int) (Instant.now().getEpochSecond() % URLS.length);
                OkHttpClient client = (OkHttpClient) this.context.getHttpEngine().getRawEngine();
                String url = URLS[l];
                this.getMessage(url, client, SAOHUA_PATTERN, fromUser, "骚...骚不出来，下次吧");
            } catch (Exception e) {
                log.error("出错了", e);
                this.context.getApi().sendText(fromUser.getUserName(), "骚...骚不出来，下次吧");
            }
        }
        if (event.getContent().contains("情话")) {
            try {
                long l = System.currentTimeMillis() % 2;
                OkHttpClient client = (OkHttpClient) this.context.getHttpEngine().getRawEngine();
                this.getMessage(QINGHUA_URL_2, client, QINGHUA_PATTERN, fromUser, "没有了，下次吧");
            } catch (Exception e) {
                log.error("出错了", e);
                this.context.getApi().sendText(fromUser.getUserName(), "出问题了哦");
            }
        }
        if (event.getContent().contains("笑话")) {
            try {
                OkHttpClient client = (OkHttpClient) this.context.getHttpEngine().getRawEngine();
                this.getMessage(JOKE_URL, client, QINGHUA_PATTERN, fromUser, "没有了，下次吧");
            } catch (Exception e) {
                log.error("出错了", e);
                this.context.getApi().sendText(fromUser.getUserName(), "出问题了哦");
            }
        }
    }

    private void getMessage(String url, OkHttpClient client, Pattern pattern, Contact fromUser, String content) throws IOException {
        Request request = new Request.Builder().url(url).build();
        try (Response response = client.newBuilder().readTimeout(10, TimeUnit.SECONDS).build().newCall(request).execute()) {
            if (response.isSuccessful() && Objects.nonNull(response.body())) {
                Matcher matcher = pattern.matcher(response.body().string());
                if (matcher.find()) {
                    this.context.getApi().sendText(fromUser.getUserName(), matcher.group(1));
                    return;
                }
            }
            log.warn("获取消息失败，请求 {} ，响应为空，url: {}", response.isSuccessful() ? "成功" : "失败", url);
            this.context.getApi().sendText(fromUser.getUserName(), content);
        }
    }
}
